import React from "react";
import * as echarts from "echarts"
import { Component } from "react";
import { withRouter } from "react-router";
// import shaoxingJson from "../../json/shaoxing.json"
// import zhujiJson from "../../json/zhuji.json"
// import keqiaoJson from "../../json/keqiao.json"
// import shangyuJson from "../../json/shangyu.json"
// import shengzhouJson from "../../json/shengzhou.json"
// import yuechengJson from "../../json/yuecheng.json"
// import xinchangJson from "../../json/xinchang.json"
import { education } from "../../js/bigscreen/education";
import {
    getSchoolNumApi, getTotalStatisticByEduIdApi, getGridNumApi,
    getGridNumByEduIdApi, getSchoolGridNumOfPeopleByEduIdApi, getSchoolGridOutNumOfPeopleByEduIdApi
} from "../../js/bigscreen/api";

import "../../css/bigscreen/mapstatistic.css";



var mapchart;
class MapStatistic extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name: "",
            statistic: { totalpatrolnum: 0, totaldangernum: 0, totalinspectnum: 0 },
            schoolNum: 0,
            gridNum: 0,
            schoolGridNumOfPeople: 0,
            isLoaded: false,
            secret: this.props.match.params.secret
        }
    }




    componentDidMount() {
        let educationId;
        this.getSchoolNum();
        // if(sessionStorage.getItem("departmentType") == "区教育局") {
        //     this.getTotalStatisticByEduId(educationId);
        // }

        if(this.props.match.params.county != undefined) {
            educationId = this.props.match.params.county
            this.getTotalStatisticByEduId(educationId);
            this.getGridNumByEduId(educationId);
            this.getSchoolGridNumOfPeopleByEduId(educationId);
            this.getSchoolGridOutNumOfPeopleByEduId(educationId);
            this.setSeesion(educationId);
        }else {
            educationId = parseInt(sessionStorage.getItem("departmentId"))
            this.getGridNumByEduId(educationId);
            this.getSchoolGridNumOfPeopleByEduId(educationId);
            this.getSchoolGridOutNumOfPeopleByEduId(educationId);
            this.setSeesion(educationId);
        }
        // this.initMap(this.state.secret);
    }


    setSeesion = (departmentId) => {
        if (sessionStorage.getItem("departmentId") == null) {
            sessionStorage.setItem("departmentId", departmentId);
        }
    }



    initMap(secret) {
        if (this.state.isLoaded) {
            var id;
            var alias;
            // 区县教育局
            if (this.props.match.params.county != undefined) {
                id = this.props.match.params.county;
                alias = education[id].alias
                this.setState({
                    name: education[id].name
                })
            // 总教育局
            } else {
                id = parseInt(sessionStorage.getItem("departmentId"));
                alias = education[sessionStorage.getItem("departmentId")].alias;
                this.setState({
                    name: education[sessionStorage.getItem("departmentId")].name
                })
            }



           
            let geoJson = require('../../json/' + alias + '.json')
            let that = this;
            echarts.registerMap(alias, geoJson);
            if (mapchart == null) {
                mapchart = echarts.init(document.getElementById("mapchart"));
            } else {
                echarts.dispose(mapchart)
                mapchart = echarts.init(document.getElementById("mapchart"));
            }
            var max = 1000; var min = 10;
            var maxSize4Pin = 50; var minSize4Pin = 40;
            const geoCoordMap = {};
            const mapFeatures = geoJson.features;
            mapFeatures.forEach(function (v) {
                const name = v.properties.name;
                geoCoordMap[name] = v.properties.center;
            })
            var convertData = (data) => {
                const res = []
                for (let i = 0; i < data.length; i++) {
                    const geoCoord = geoCoordMap[data[i].name]
                    if (geoCoord) {
                        res.push({
                            name: data[i].name,
                            id: data[i].id,
                            value: geoCoord.concat(data[i].value)
                        })
                    }
                }
                return res
            }
            var option = {
                geo: {
                    map: alias,
                    aspectScale: 0.75, // 长宽比
                    zoom: 0.7,
                    roam: false,
                    itemStyle: {
                        areaColor: '#0085EC',
                        borderWidth: 3,
                        borderColor: '#0085EC',
                        shadowColor: '#0085EC',
                        shadowBlur: 10
                    },
                    emphasis: {
                        borderWidth: 0,
                        label: {
                            show: false
                        }
                    },
                    silent: true,
                    layoutCenter: ['40%', '50.5%'],
                    layoutSize: '100%',
                },

                series: [
                    {
                        type: 'map',
                        map: alias,
                        itemStyle: {
                            areaColor: 'rgba(45, 136, 255, 0.8)',
                            borderColor: '#0a53e9',
                            shadowColor: '#092f8f',
                            shadowBlur: 30
                        },
                        emphasis: {
                            label: {
                                show: false,
                            },
                            itemStyle: {
                                areaColor: 'rgb(10, 45, 147)',

                            }
                        },
                        select: {
                            label: {
                                show: false,
                            },
                            itemStyle: {
                                areaColor: 'rgb(10, 45, 147)',
                            }
                        },
                        zoom: 0.7,
                        layoutCenter: ['40%', '50%'],
                        layoutSize: '100%',
                        // shading:'color',
                        data: education[sessionStorage.getItem("departmentId")].list,
                    },
                    {
                        type: 'scatter',
                        coordinateSystem: 'geo',
                        symbolSize: function (val) {
                            const size = val[2] / 5
                            return 15
                        },
                        label: {
                            show: true,
                            position: 'left',
                            color: '#FFFFFF',
                            formatter: '{b}'
                        },
                        itemStyle: {
                            color: '#003372'
                        },
                        data: convertData(education[sessionStorage.getItem("departmentId")].list)
                    },
                    {
                        type: 'effectScatter',
                        coordinateSystem: 'geo',
                        symbolSize: function (val) {
                            // val[2] / 25
                            return 15
                        },
                        showEffectOn: 'render',
                        rippleEffect: {
                            brushType: 'stroke'
                        },
                        label: {
                            show: false
                        },
                        itemStyle: {
                            color: '#dfae10',
                            shadowBlur: 10,
                            shadowColor: '#0085EC'
                        },
                        emphasis: {
                            scale: true
                        },
                        data: convertData(education[sessionStorage.getItem("departmentId")].list)
                    },
                    {
                        type: 'scatter',
                        coordinateSystem: 'geo',
                        symbol: 'pin',
                        symbolSize: function (val) {
                            const a = (maxSize4Pin - minSize4Pin) / (max - min)
                            let b = minSize4Pin - a * min
                            b = maxSize4Pin - a * max
                            return a * val[2] + b
                        },

                        label: {
                            show: true,
                            color: '#fff',
                            fontSize: 12,
                            formatter: '{@[2]}'
                        },
                        itemStyle: {
                            color: '#dfae10'
                        },
                        data: convertData(education[sessionStorage.getItem("departmentId")].list)
                    }

                ],
            };

            window.onresize = function () {
                mapchart.resize();
            }
            mapchart.setOption(option);
            if (sessionStorage.getItem("departmentType") == "教育局" || sessionStorage.getItem("departmentId") == 0) {
                mapchart.on('click', function (params) {
                    if (that.props.match.params.county == undefined) {
                        that.props.history.push({
                            pathname: '/edubigscreen/county/' + params.data.id + '/' + secret,
                        });
                    } else {
                        that.props.history.goBack();
                    }
                })
            }

        }


    }


    getSchoolNum = async () => {
        if (this.props.match.params.county == undefined) {
            try {
                let sum = 0;
                for (const item of education[sessionStorage.getItem("departmentId")].list) {
                    const res = await getSchoolNumApi(item.id);
                    item.value = res.data.schoolNum;
                    sum += res.data.schoolNum;
                }
                this.props.schoolNum(sum);
                this.setState({
                    isLoaded: true
                }, () => {
                    this.initMap(this.state.secret);
                })
                
            } catch (e) {
                console.log(e)
            }

        } else {
            try {
                let id = this.props.match.params.county
                const res = await getSchoolNumApi(id)
                education[id].list.push({
                    id: id,
                    name: education[id].name,
                    value: res.data.schoolNum
                })
                this.props.schoolNum(res.data.schoolNum);
                this.setState({
                    isLoaded: true
                })
                this.setState({
                    isLoaded: true
                }, () => {
                    this.initMap(this.state.secret);
                })
            } catch (e) {
                console.log(e);
            }

        }

    }

    getTotalStatisticByEduId = (educationId) => {
        getTotalStatisticByEduIdApi(educationId).then((res) => {
            if (res.data.statistic) {
                this.setState({
                    statistic: res.data.statistic
                })
                this.props.statistic(res.data.statistic);
            }
        }).catch((e) => {
            console.log(e);
        })
    }

    // getGridNum = () => {
    //     getGridNumApi().then((res) => {
    //         if (res.data) {
    //             this.setState({
    //                 gridNum: res.data.gridnum
    //             })
    //             this.props.gridNum(res.data.gridnum);
    //         }
    //     }).catch((e) => {
    //         console.log(e);
    //     })
    // }

    getGridNumByEduId = (educationId) => {
        getGridNumByEduIdApi(educationId).then((res) => {
            if (res.data) {
                this.setState({
                    gridNum: res.data.gridnum
                })
                this.props.gridNum(res.data.gridnum);
            }
        }).catch((e) => {
            console.log(e);
        })
    }


    getSchoolGridNumOfPeopleByEduId = (educationId) => {
        getSchoolGridNumOfPeopleByEduIdApi(educationId).then((res) => {
            if (res.data) {
                this.setState({
                    schoolGridNumOfPeople: res.data.schoolgridnumofpeople
                })
                this.props.schoolGridNumOfPeople(res.data.schoolgridnumofpeople);
            }
        }).catch((e) => {
            console.log(e);
        })
    }

    getSchoolGridOutNumOfPeopleByEduId = (educationId) => {
        getSchoolGridOutNumOfPeopleByEduIdApi(educationId).then((res) => {
            if (res.data) {
                this.setState({
                    schoolGridOutNumOfPeople: res.data.schoolgridoutnumofpeople
                })
                this.props.schoolGridOutNumOfPeople(res.data.schoolgridoutnumofpeople);
            }
        }).catch((e) => {
            console.log(e);
        })
    }








    render() {
        return (
            <div className="mapborder">
                <div className="mapheader">
                    <span className="mapheadertxt">{this.state.name}师生安全网格总览</span>
                </div>
                <div className="netstatistic">
                    <ul>
                        <li className="netitem">
                            <svg class="icon" aria-hidden="true">
                                <use xlinkHref="#icon-wg"></use>
                            </svg>
                            <div className="net">
                                <span className="name">校内网格数</span>
                                <span className="num">{this.state.gridNum}</span>
                                <span className="unit">个</span>
                            </div>
                        </li>
                        <li className="netitem">
                            <svg class="icon" aria-hidden="true">
                                <use xlinkHref="#icon-renyuanguanli1"></use>
                            </svg>
                            <div className="net">
                                <span className="name">校园网格人员数</span>
                                <span className="num">{this.state.schoolGridNumOfPeople}</span>
                                <span className="unit">个</span>
                            </div>
                        </li>
                        {/* <li className="netitem">
                            <i className="iconfont icon-renyuan"></i>
                            <div className="net">
                                <span className="name">校外网格人员数</span>
                                <span className="num">0</span>
                                <span className="unit">个</span>
                            </div>
                        </li> */}
                    </ul>
                    {this.props.match.params.county ? (
                        <ul>
                            <li className="netitem">
                                <i className="iconfont icon-xunjian"></i>
                                <svg class="icon" aria-hidden="true">
                                    <use xlinkHref="#icon-xunjian3"></use>
                                </svg>
                                <div className="net">
                                    <span className="name">累计安全巡检数</span>
                                    <span className="num">{this.state.statistic.totalinspectnum}</span>
                                    <span className="unit">次</span>
                                </div>
                            </li>
                            <li className="netitem">
                                <svg class="icon" aria-hidden="true">
                                    <use xlinkHref="#icon-dianzixungeng"></use>
                                </svg>
                                <div className="net">
                                    <span className="name">累计安全巡更数</span>
                                    <span className="num">{this.state.statistic.totalpatrolnum}</span>
                                    <span className="unit">次</span>
                                </div>
                            </li>
                            <li className="netitem">
                                <i className="iconfont icon-yinhuandianwei"></i>
                                <svg class="icon" aria-hidden="true">
                                    <use xlinkHref="#icon-yinhuandianwei"></use>
                                </svg>
                                <div className="net">
                                    <span className="name">累计安全隐患数</span>
                                    <span className="num">{this.state.statistic.totaldangernum}</span>
                                    <span className="unit">个</span>
                                </div>
                            </li>
                        </ul>
                    ) : (<div style={{ display: 'none' }}></div>)}
                </div>
                <div id="mapchart"></div>
            </div>

        )
    }
}

export default withRouter(MapStatistic)